import { createSlice } from '@reduxjs/toolkit'
import { setToken as _setToken, getToken, removeToken } from '@/utils'
import { loginAPI, getUserProfileAPI } from '@/apis/user'

const userStore = createSlice({
  // 名称
  name: 'user',
  // 状态初始值
  initialState: {
    token: getToken() || '',
    userInfo: {}
  },
  // 同步修改方法
  reducers: {
    setToken (state, action) {
      state.token = action.payload
      _setToken(action.payload)
    },
    setUserInfo (state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo (state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  }
})


// 解构出 actionCreate
const { setToken, setUserInfo, clearUserInfo } = userStore.actions

// 异步修改方法
const fetchLogin = (val) => {
  return async (dispatch) => {
    const res = await loginAPI(val)
    dispatch(setToken(res.data.token))
  }
}
// 获取用户信息的异步方法
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await getUserProfileAPI()
    dispatch(setUserInfo(res.data))
  }
}

// 获取 reducer 函数
const userReducer = userStore.reducer

export { setToken, fetchLogin, fetchUserInfo, clearUserInfo }

export default userReducer